package com.universal.schedule;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.universal.schedule.adapter.ImagePublishAdapter;
import com.universal.schedule.db.DBManager;
import com.universal.schedule.db.DatabaseHelper;
import com.universal.schedule.enity.ImageItem;
import com.universal.schedule.utils.CustomConstants;
import com.universal.schedule.utils.IntentConstants;

import java.io.File;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class EditActivity extends Activity implements View.OnClickListener {
	private EditText content;
	private TextView publicTextView;
	private ArrayList<String> imageUrlList = new ArrayList<String>();
	private GridView mGridView;
	private ImagePublishAdapter mAdapter;
	public List<ImageItem> mDataList = new ArrayList<ImageItem>();

	// private Button bt;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit);
		initView1();
		initData();
		initView();
	}

	private void initView1() {
		// TODO Auto-generated method stub
		content = (EditText) findViewById(R.id.forum_content);
		publicTextView = (TextView) findViewById(R.id.edit_public);
		publicTextView.setOnClickListener(this);
		mDialog = showLoadingDialog(this);
		content.clearFocus();
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
	}

	@Override
	protected void onPause() {
		super.onPause();
		// saveTempToPref();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		saveTempToPref();
	}

	private void saveTempToPref() {
		SharedPreferences sp = getSharedPreferences(CustomConstants.APPLICATION_NAME, MODE_PRIVATE);
		String prefStr = JSON.toJSONString(mDataList);
		sp.edit().putString(CustomConstants.PREF_TEMP_IMAGES, prefStr).commit();

	}

	private void getTempFromPref() {
		SharedPreferences sp = getSharedPreferences(CustomConstants.APPLICATION_NAME, MODE_PRIVATE);
		String prefStr = sp.getString(CustomConstants.PREF_TEMP_IMAGES, null);
		if (!TextUtils.isEmpty(prefStr)) {
			List<ImageItem> tempImages = JSON.parseArray(prefStr, ImageItem.class);
			mDataList = tempImages;
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
		removeTempFromPref();
	}

	private void removeTempFromPref() {
		SharedPreferences sp = getSharedPreferences(CustomConstants.APPLICATION_NAME, MODE_PRIVATE);
		sp.edit().remove(CustomConstants.PREF_TEMP_IMAGES).commit();
	}

	@SuppressWarnings("unchecked")
	private void initData() {
		getTempFromPref();
		List<ImageItem> incomingDataList = (List<ImageItem>) getIntent()
				.getSerializableExtra(IntentConstants.EXTRA_IMAGE_LIST);
		if (incomingDataList != null) {
			mDataList.addAll(incomingDataList);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		notifyDataChanged(); // 当在ImageZoomActivity中删除图片时，返回这里需要刷新
	}

	private void notifyDataChanged() {
		mAdapter.notifyDataSetChanged();
	}

	public void initView() {
		mGridView = (GridView) findViewById(R.id.gridview);
		mGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
		mAdapter = new ImagePublishAdapter(this, mDataList);
		mGridView.setAdapter(mAdapter);
		mGridView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (position == getDataSize()) {
					new PopupWindows(EditActivity.this, mGridView);
				} else {
					Intent intent = new Intent(EditActivity.this, ImageZoomActivity.class);
					intent.putExtra(IntentConstants.EXTRA_IMAGE_LIST, (Serializable) mDataList);
					intent.putExtra(IntentConstants.EXTRA_CURRENT_IMG_POSITION, position);
					startActivityForResult(intent, 5);
				}
			}
		});
		// sendTv = (TextView) findViewById(R.id.action);
		// sendTv.setText("发送");
		// sendTv.setOnClickListener(new OnClickListener()
		// {
		//
		// public void onClick(View v)
		// {
		// removeTempFromPref();
		// System.exit(0);
		// //TODO 这边以mDataList为来源做上传的动作
		// }
		// });
	}

	private int getDataSize() {
		return mDataList == null ? 0 : mDataList.size();
	}

	private int getAvailableSize() {
		int availSize = CustomConstants.MAX_IMAGE_SIZE - mDataList.size();
		if (availSize >= 0) {
			return availSize;
		}
		return 0;
	}

	public String getString(String s) {
		String path = null;
		if (s == null)
			return "";
		for (int i = s.length() - 1; i > 0; i++) {
			s.charAt(i);
		}
		return path;
	}

	public class PopupWindows extends PopupWindow {

		public PopupWindows(Context mContext, View parent) {

			View view = View.inflate(mContext, R.layout.item_popupwindow, null);
			view.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
			ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.push_bottom_in_2));

			setWidth(LayoutParams.MATCH_PARENT);
			setHeight(LayoutParams.MATCH_PARENT);
			setFocusable(true);
			setOutsideTouchable(true);
			setContentView(view);
			showAtLocation(parent, Gravity.BOTTOM, 0, 0);
			update();

			Button bt1 = (Button) view.findViewById(R.id.item_popupwindows_camera);
			Button bt2 = (Button) view.findViewById(R.id.item_popupwindows_Photo);
			Button bt3 = (Button) view.findViewById(R.id.item_popupwindows_cancel);
			bt1.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
                    if (ContextCompat.checkSelfPermission(EditActivity.this, Manifest.permission.CAMERA)
                            != PackageManager.PERMISSION_GRANTED ||
                            ContextCompat.checkSelfPermission(EditActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                                    != PackageManager.PERMISSION_GRANTED ||
                            ContextCompat.checkSelfPermission(EditActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                    != PackageManager.PERMISSION_GRANTED){
                        ActivityCompat.requestPermissions(EditActivity.this,
                                new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE,
                                        Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
                    }else {
                        takePhoto();
                        dismiss();
                    }
                }
			});
			bt2.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
                    if (ContextCompat.checkSelfPermission(EditActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            != PackageManager.PERMISSION_GRANTED){
                        ActivityCompat.requestPermissions(EditActivity.this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
                    }else {
                        Intent intent = new Intent(EditActivity.this, ImageBucketChooseActivity.class);
                        intent.putExtra(IntentConstants.EXTRA_CAN_ADD_IMAGE_SIZE, getAvailableSize());
                        startActivityForResult(intent, 2);
                        dismiss();
                    }
				}
			});
			bt3.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					dismiss();
				}
			});

		}
	}

	private static final int TAKE_PICTURE = 0x000000;
	private String path = "";
	private Dialog mDialog;
	private String userContent;

	public void takePhoto() {

		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		File vFile = new File(Environment.getExternalStorageDirectory() + "/myimage/",
				String.valueOf(System.currentTimeMillis()) + ".jpg");
		if (!vFile.exists()) {
			File vDirPath = vFile.getParentFile();
			vDirPath.mkdirs();
		} else {
			if (vFile.exists()) {
				vFile.delete();
			}
		}
		path = vFile.getPath();
        Uri cameraUri ;
        //cameraUri= Uri.fromFile(vFile);
       if (Build.VERSION.SDK_INT >= 24){
            cameraUri = FileProvider.getUriForFile(this,"com.universal.schedule.fileprovider",vFile);
        }else {
            cameraUri = Uri.fromFile(vFile);
        }
		openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
		startActivityForResult(openCameraIntent, TAKE_PICTURE);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
			case TAKE_PICTURE:
				if (mDataList.size() < CustomConstants.MAX_IMAGE_SIZE && resultCode == -1 && !TextUtils.isEmpty(path)) {
					ImageItem item = new ImageItem();
					item.sourcePath = path;
					mDataList.add(item);
				}
				break;
			case 2:
				break;
		}
		if (resultCode == 1) {
			getTempFromPref();
			if (data != null) {
				List<ImageItem> incomingDataList = (List<ImageItem>) data
						.getSerializableExtra(IntentConstants.EXTRA_IMAGE_LIST);
				if (incomingDataList != null) {
					mDataList.addAll(incomingDataList);
				}
			} else {
				Toast.makeText(this, "没有返回数据", Toast.LENGTH_LONG).show();
			}
		}
		if (resultCode == 5) {
			mDataList.clear();
			if (data != null) {
				List<ImageItem> incomingDataList = (List<ImageItem>) data
						.getSerializableExtra(IntentConstants.EXTRA_IMAGE_LIST);
				if (incomingDataList != null) {
					mDataList.addAll(incomingDataList);
					notifyDataChanged();
				} else {
					Toast.makeText(this, "没有返回数据", Toast.LENGTH_LONG).show();
				}
			}
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
			case R.id.edit_public:

				Toast.makeText(EditActivity.this, "保存成功", Toast.LENGTH_LONG).show();
				userContent = content.getText().toString();
				if (!userContent.equals("")) {
					if (mDataList.size() != 0) {
						// mDialog.show();
						for (int i = 0; i < mDataList.size(); i++) {
							Date d = new Date();
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							String dateNowStr = sdf.format(d);
							ContentValues cv = new ContentValues();
							cv.put(DatabaseHelper.COLUMN_DIARY_IMAGE_URL, mDataList.get(i).sourcePath);
							cv.put(DatabaseHelper.COLUMN_DIARY_MESSAGE, userContent);
							cv.put(DatabaseHelper.COLUMN_DIARY_TIME, dateNowStr);
							long insert = DBManager.getInstance(EditActivity.this).insert(DatabaseHelper.DIARY_TABLE,
									DatabaseHelper.COLUMN_DIARY_MESSAGE, cv);
						}

					} else {
						Date d = new Date();
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						String dateNowStr = sdf.format(d);
						ContentValues cv = new ContentValues();
						cv.put(DatabaseHelper.COLUMN_DIARY_IMAGE_URL, "");
						cv.put(DatabaseHelper.COLUMN_DIARY_MESSAGE, userContent);
						cv.put(DatabaseHelper.COLUMN_DIARY_TIME, dateNowStr);
						DBManager.getInstance(EditActivity.this).insert(DatabaseHelper.DIARY_TABLE,
								DatabaseHelper.COLUMN_DIARY_MESSAGE, cv);
					}
					finish();
				} else {
					Toast.makeText(EditActivity.this, "日记内容不能为空!", Toast.LENGTH_SHORT).show();
				}
				break;
		}
	}

	/**
	 * 圆形等待加载进度条
	 */
	public static Dialog showLoadingDialog(Context mContext) {

		LayoutInflater inflaters = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view2 = inflaters.inflate(R.layout.dialog_waiting, null);
		Dialog loadingDialog = new Dialog(mContext, R.style.paringTheme);
		loadingDialog.setCancelable(true);
		loadingDialog.setContentView(view2);
		loadingDialog.setCanceledOnTouchOutside(false);
		return loadingDialog;
	}


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    Intent intent = new Intent(EditActivity.this, ImageBucketChooseActivity.class);
                    intent.putExtra(IntentConstants.EXTRA_CAN_ADD_IMAGE_SIZE, getAvailableSize());
                    startActivityForResult(intent, 2);
                }else {
                    Toast.makeText(this,"you denied the permission",Toast.LENGTH_SHORT).show();
                }
                break;
            case 2:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    takePhoto();
                }else {
                    Toast.makeText(this,"you denied the permission",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }
}
